package com.sunlee.admin.api.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sunlee.admin.api.module.security.user.SecurityUser;
import com.sunlee.admin.api.module.security.user.UserDetail;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 公共字段，自动填充值
 *
 * @author sunlee
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private static final String CREATE_DATE = "createDate";
    private static final String CREATOR = "creator";
    private static final String UPDATE_DATE = "updateDate";
    private static final String UPDATER = "updater";
    private static final String DEPT_ID = "deptId";

    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetail user = SecurityUser.getUser();
        Date date = new Date();

        //创建者
        strictInsertFill(metaObject, CREATOR, Long.class, user.getId());

        //创建时间
        strictInsertFill(metaObject, CREATE_DATE, Date.class, date);

        //创建者所属部门
        strictInsertFill(metaObject, DEPT_ID, Long.class, user.getDeptId());

        //更新者
        strictInsertFill(metaObject, UPDATER, Long.class, user.getId());

        //更新时间
        strictInsertFill(metaObject, UPDATE_DATE, Date.class, date);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新者
        strictUpdateFill(metaObject, UPDATER, Long.class, SecurityUser.getUserId());

        Date date = new Date();
        //更新时间
        strictUpdateFill(metaObject, UPDATE_DATE, Date.class, date);
        //strictUpdateFill有时不生效，先暂时兼容一下
        boolean hasUpdateDate = metaObject.hasSetter(UPDATE_DATE);
        if (hasUpdateDate) {
            setFieldValByName(UPDATE_DATE, date, metaObject);
        }
    }
}
